// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const {
	validate,
	validations
} = require('ws-chat-common').validate
const jm = require("ws-chat-common").jm
const db = uniCloud.database()
const respond = require("ws-chat-common").respond
const {
	getToken,
	verifyToken
} = require('ws-chat-common').jwt
module.exports = {
	_after: respond.afterHandle,
	// 目前账号密码登录  后续在进行天降
	async login(e) {
		const body = validate(validations.user.login, e)
		const {
			data
		} = await db.collection('sys_user').where({
			phone: e.phone
		}).get()
		if (Array.isArray(data) && data.lenght > 0) {
			throw new Error('账户或密码错误')
		}
		const user = data[0]
		if (!jm.comparebcrypt(body.password, user.password)) {
			throw new Error('账户或密码错误')
		}
		delete user.password
		const t = getToken(user)
		return {
			...user,
			token: t
		}

	},
	async register(e) {
		const {
			data: have
		} = await db.collection("sys_user").where({
			phone: e.phone
		}).get()
		if (Array.isArray(have) && have.length > 0) {
			throw new Error('手机号已注册')
		}
		e.password = jm.setbcrypt(e.password)
		const {
			id
		} = await db.collection('sys_user')
			.add(e)
		const {
			data
		} = await db.collection('sys_user').where({
				_id: id
			})
			.get()


		return data
	},
	async getUserInfo(e) {
		const {
			_id
		} = verifyToken(e)

		const {
			data
		} = await db.collection('sys_user').field({
				password: false
			}).where({
				_id: _id,
			})
			.get()
		return data[0]
	}
}